package com.buydeem.share.hystrixdemo;

import com.buydeem.share.hystrixdemo.model.User;
import com.buydeem.share.hystrixdemo.service.UserService;
import com.netflix.hystrix.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;


/**
 * hystrix 基础使用
 * @author zengchao
 * @version 1.0.0
 * @ClassName App1.java
 * @Description TODO
 * @createTime 2021年03月29日 20:35:00
 */
@Slf4j
public class App1 {

    public static void main(String[] args){
        //正常执行
        QueryUserCommand command = new QueryUserCommand("mac");
        User mac = command.execute();
        log.info(mac.toString());
        //异常调用fallback
        QueryUserCommand failCommand = new QueryUserCommand("tom");
        User tom = failCommand.execute();
        log.info(tom.toString());

    }
}

@Slf4j
class QueryUserCommand extends HystrixCommand<User> {
    private final String name;
    private final UserService userService;

    public QueryUserCommand(String name) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("group_key"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("command_key")));
        this.name = name;
        this.userService = new UserService();
    }

    @Override
    protected User run() throws Exception {
        if (Objects.equals("tom",name)){
            throw new RuntimeException("xxxx");
        }
        User user = userService.queryUser(name);
        log.info("query result:{}",user);
        return user;
    }

    @Override
    protected User getFallback() {
        log.error("query fail");
        return new User("fallback", 18, "未知用户");
    }
}
